#include "udpsocket.h"
#include <QUdpSocket>
#include <QtGui>
#include <cstdlib>
#include <stdio.h>
#include <QtNetwork/QNetworkInterface>
#include <QDebug>
#include <systemfile.h>
#include <QHostInfo>
#define udp_send_port 5000
udpSocket::udpSocket(systemFile *point)
{
   this->sysInfo = point;
   dev_reboot=false;
}

QString udpSocket::getIP()  //获取ip地址
{
    //    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    //    foreach (QHostAddress address, list)
    //    {
    //        if(address.protocol() == QAbstractSocket::IPv4Protocol)
    //            //我们使用IPv4地址
    //            return address.toString();
    //    }
    QString localHostName = QHostInfo::localHostName();
    qDebug() <<"localHostName:"<<localHostName;
    QHostInfo info = QHostInfo::fromName(localHostName);
    foreach(QHostAddress address,info.addresses())
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
            qDebug() <<"IPV4 Address: "<< address.toString();
        return address.toString();
    }
    return 0;
}

void udpSocket::udp_send()
{
    QString AskStr;
    QString HeadStr;
    QByteArray AskBuffer;
    QTextCodec *codecgc = QTextCodec::codecForName("GB2312"); //转化编码
    HeadStr = "::" + sysInfo->mac;
    AskStr = QString("%1,BEGIN,%2,%3,%4,%5\r\n").arg(HeadStr).arg(sysInfo->galleryName).arg(sysInfo->galleryNumber).arg(sysInfo->localIp).arg("PARK");
    AskBuffer = codecgc->fromUnicode(AskStr);
    udpBroadLink->writeDatagram(AskBuffer,AskBuffer.count(),QHostAddress::Broadcast,udp_send_port);
}

void udpSocket::udp_broadcast_reciver_data()
{
    QByteArray data;
    QByteArray askBuffer;
    QHostAddress sender;
    quint16 senderPort;
    QString udpdata;
    if(udpBroadLink->hasPendingDatagrams())
    {
        QString askStr;
        QString headStr;
        data.resize(udpBroadLink->pendingDatagramSize());
        udpBroadLink->readDatagram(data.data(),data.size(),&sender,&senderPort);
        QStringList list;
        QTextCodec *codec = QTextCodec::codecForName("GB2312"); //转化编码
        udpdata = codec->toUnicode(data);
        qDebug()<<"ip:"<<sender<<"port:"<<QString::number(senderPort)<<"cmd:"<<udpdata;
        if(sender==QHostAddress(getIP()))
        {
            return;
        }
        //包头
        headStr = "::" + sysInfo->mac;
        list= udpdata.split(',');
        //广播地址
        if(list[0] == "::FF:FF:FF:FF:FF:FF" && list[1] == "FIND")
        {
            askStr = QString("%1,FIND,%2,%3,%4,%5\r\n").arg(headStr).arg(sysInfo->galleryName).arg(sysInfo->galleryNumber).arg(sysInfo->localIp).arg("PARK");
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress::Broadcast,udp_send_port);
            return;
        }
        else if(list[0] != headStr)
        {
            return;
        }
        //等于本机MAC
        if(list[1] == "GET" && list.count()==2)
        {
            QString askStr;
            askStr = QString("%1,GET,NET,%2,%3,%4").arg(headStr).arg(sysInfo->localIp).arg(sysInfo->mask).arg(sysInfo->gatewayIp);
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress(sender),udp_send_port);
            //列出所有分组
            foreach(QString group,sysInfo->devSetting->childGroups())
            {
                askStr = QString("%1,GET,%2").arg(headStr).arg(group);
                //列出所有键值
                sysInfo->devSetting->beginGroup(group);
                foreach(QString key,sysInfo->devSetting->childKeys())
                {
                    askStr.append(",");
                    askStr.append(sysInfo->devSetting->value(key).toString());
                }
                askStr.append("\r\n");
                sysInfo->devSetting->endGroup();
                //
                askBuffer = codec->fromUnicode(askStr);
                udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress(sender),udp_send_port);
            }
            return;
        }
        else if(list[1] == "REBOOT")
        {
            askStr = QString("%1,REBOOT,OK\r\n").arg(headStr);
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress(sender),udp_send_port);
            dev_reboot=true;
            return;
        }
        else if(list[1] == "SET")
        {
            qDebug()<<"SET";
            if(list[2] == "NET")
            {
                sysInfo->localIp = list[3];
                sysInfo->mask = list[4];
                sysInfo->gatewayIp = list[5];
                sysInfo->writeInterfaces();
            }
            else if(list[2] == "SERVER")
            {
                sysInfo->devSetting->beginGroup(list[2]);
                sysInfo->devSetting->setValue("serverIp",list[3].trimmed());
                sysInfo->devSetting->setValue("serverUrl",list[4].trimmed());
                sysInfo->devSetting->setValue("updataPicture",list[5].trimmed());
                sysInfo->devSetting->setValue("updataTime",list[6].trimmed());
                sysInfo->devSetting->setValue("downTime",list[7].trimmed());
                sysInfo->devSetting->setValue("userName",list[8].trimmed());
                sysInfo->devSetting->setValue("passWord",list[9].trimmed());
                sysInfo->devSetting->setValue("datebaseName",list[10].trimmed());
                sysInfo->devSetting->endGroup();
            }
            else if(list[2] == "DEVICE")
            {
                sysInfo->devSetting->beginGroup(list[2]);
                sysInfo->galleryName = list[3].trimmed();
                sysInfo->devSetting->setValue("galleryName",sysInfo->galleryName);
                sysInfo->galleryNumber = list[4].trimmed();
                sysInfo->devSetting->setValue("galleryNumber",sysInfo->galleryNumber);
                sysInfo->regNumber = list[5].trimmed();
                sysInfo->devSetting->setValue("regNumber",sysInfo->regNumber);
                sysInfo->heart = list[6].trimmed().toInt();
                sysInfo->devSetting->setValue("heart",sysInfo->heart);
                sysInfo->path = list[7].trimmed();
                sysInfo->devSetting->setValue("path",sysInfo->path);
                sysInfo->devSetting->endGroup();
            }
            else if(list[2] == "CAMERA")
            {
                sysInfo->devSetting->beginGroup(list[2]);
                sysInfo->devSetting->setValue("cameraInIp",list[3].trimmed());
                sysInfo->devSetting->setValue("cameraOutIp",list[4].trimmed());
                sysInfo->devSetting->setValue("savePicture",list[5].trimmed());
                sysInfo->devSetting->setValue("vehicleFlag",list[6].trimmed());
                sysInfo->devSetting->endGroup();
            }
            else if(list[2] == "MODEL")
            {
                sysInfo->devSetting->beginGroup(list[2]);
                sysInfo->devSetting->setValue("model",list[3].trimmed());
                sysInfo->devSetting->setValue("tempCarIn",list[4].trimmed());
                sysInfo->devSetting->setValue("passFlag",list[5].trimmed());
                sysInfo->devSetting->setValue("first_down",list[6].trimmed());
                sysInfo->devSetting->setValue("park_type",list[7].trimmed());
                sysInfo->devSetting->endGroup();
            }
            else if(list[2]=="TIME")
            {
                QString time=list[3].trimmed();
                qDebug()<<"before changed time :"<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
                char cmd[100];
                qDebug()<<"time"<<time;
                sprintf(cmd,"date -s '%s'",time.toLatin1().data());
                ::system(cmd);
                ::system("hwclock -w");
                qDebug()<<"after changed time :"<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            }
            askStr = QString("%1,SET,%2,OK\r\n").arg(headStr).arg(list[2]);
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress(sender),senderPort);
        }//end if set
        /*else if(list[1] == "RESET")
        {
            reset_ini();
            askStr = QString("%1,RESET,OK\r\n").arg(headStr);
            askBuffer = codec->fromUnicode(askStr);
            udpBroadLink->writeDatagram(askBuffer,askBuffer.count(),QHostAddress(sender),senderPort);
            return;
        }*/

    }
}

void udpSocket::reset_ini()
{
    QFile file("camera.ini");
    QString as,bs,cs,ds;
    if(file.open(QFile::ReadOnly))
    {
        as=file.readLine().trimmed();
        bs=file.readLine().trimmed();
        cs=file.readLine().trimmed();
        ds=file.readLine().trimmed();
        file.close();
        if(file.open(QFile::WriteOnly))
        {
            QTextStream out1(&file);
            out1<<as<<"\r\n"<<bs<<"\r\n"<<cs<<"\r\n"<<"0"<<"\r\n";
            out1.seek(out1.pos());//定位文件当前
            file.close();
        }
    }else{
        QFile file1("camera.ini");
        if(file1.open(QFile::WriteOnly))
        {
            QTextStream out1(&file1);
            out1.seek(out1.pos());//定位文件当前
            //file.write("\r\n");//换行符
            // ip="127.0.0.1";
            file1.close();
        }
    }
}

void udpSocket::first_down_reset()
{
    sysInfo->first_down=0;
    sysInfo->devSetting->beginGroup("MODEL");
    sysInfo->devSetting->setValue("model",sysInfo->model);
    sysInfo->devSetting->setValue("tempCarIn",sysInfo->tempCarIn);
    sysInfo->devSetting->setValue("passFlag",sysInfo->passFlag);
    sysInfo->devSetting->setValue("park_type",sysInfo->park_type);
    sysInfo->devSetting->setValue("first_down",sysInfo->first_down);
    sysInfo->devSetting->endGroup();
}
